package middleware

import (
	"github.com/gin-gonic/gin"
	jwt2 "github.com/golang-jwt/jwt/v4"
	"github.com/vueadmin/pkg/jwt"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
)

// jwt解码
func JwtVerifyMiddleware(jwtConfig string) gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		if conv.IsEmpty(token) {
			response.Fail(c, "token值不能为空!")
			c.Abort()
			return
		}
		data, err := jwt.NewJwt(jwtConfig).ParseToken(token)
		if err != nil {
			if err == jwt.TokenExpired {
				response.Fail(c, "token已过期!")
				c.Abort()
				return
			} else {
				response.Fail(c, "token解析错误")
				c.Abort()
				return
			}
		}
		for k, v := range data.(jwt2.MapClaims) {
			c.Set(k, v)
		}
		c.Next()
	}
}
